<template>
  <div class="city-selector s_city" @click.stop>
    <span>{{ selectedCity || '四川' }}</span>
    <div class="s_city_bg" v-show="showDropdown">
      <div class="s_city_t"></div>
      <div class="s_city_c">
        <h2>请选择所在的收货地区</h2>
        <table border="0" class="c_tab" cellspacing="0" cellpadding="0">
          <tr v-for="group in cityGroups" :key="group.letter">
            <th>{{ group.letter }}</th>
            <td class="c_h">
              <span 
                v-for="city in group.cities" 
                :key="city"
                :class="{ 'c_check': city === selectedCity }"
                @click="selectCity(city)"
              >
                {{ city }}
              </span>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CitySelector',
  props: {
    modelValue: {
      type: String,
      default: '四川'
    }
  },
  emits: ['update:modelValue', 'change'],
  data() {
    return {
      showDropdown: false,
      selectedCity: this.modelValue,
      cityGroups: [
        { letter: 'A', cities: ['安徽', '澳门'] },
        { letter: 'B', cities: ['北京'] },
        { letter: 'C', cities: ['重庆'] },
        { letter: 'F', cities: ['福建'] },
        { letter: 'G', cities: ['广东', '广西', '贵州', '甘肃'] },
        { letter: 'H', cities: ['河北', '河南', '黑龙江', '海南', '湖北', '湖南'] },
        { letter: 'J', cities: ['江苏', '吉林', '江西'] },
        { letter: 'L', cities: ['辽宁'] },
        { letter: 'N', cities: ['内蒙古', '宁夏'] },
        { letter: 'Q', cities: ['青海'] },
        { letter: 'S', cities: ['上海', '山东', '山西', '四川', '陕西'] },
        { letter: 'T', cities: ['台湾', '天津'] },
        { letter: 'X', cities: ['西藏', '香港', '新疆'] },
        { letter: 'Y', cities: ['云南'] },
        { letter: 'Z', cities: ['浙江'] }
      ]
    }
  },
  methods: {
    toggleDropdown() {
      this.showDropdown = !this.showDropdown
    },
    selectCity(city) {
      this.selectedCity = city
      this.showDropdown = false
      this.$emit('update:modelValue', city)
      this.$emit('change', city)
    },
    handleClickOutside(event) {
      if (!this.$el.contains(event.target)) {
        this.showDropdown = false
      }
    }
  },
  mounted() {
    this.$el.addEventListener('click', this.toggleDropdown)
    document.addEventListener('click', this.handleClickOutside)
  },
  beforeUnmount() {
    this.$el.removeEventListener('click', this.toggleDropdown)
    document.removeEventListener('click', this.handleClickOutside)
  },
  watch: {
    modelValue(newVal) {
      this.selectedCity = newVal
    }
  }
}
</script>

<style scoped>
.city-selector {
  position: relative;
}

.c_tab {
  width: 235px;
  margin-top: 10px;
}
</style>